package blog

import (
	"dustbe/database"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"

	// "fmt"

	"github.com/gin-gonic/gin"
)

func FetchArticleByName(c *gin.Context) {
	blogName := c.Query("blogName")
	blogNode, err := database.QueryBlogByName(blogName)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4002, "data": "数据库错误"})
		return
	}

	seq := blogNode["seq"].(int)
	blogPath := fmt.Sprintf("%s/%d.md", blogRoot, seq)

	fileByte, err := ioutil.ReadFile(blogPath)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": err.Error()})
		return
	}



	blogNode["text"] = string(fileByte)
	c.JSON(http.StatusOK, gin.H{"code": 200, "data": blogNode})
}

func FetchArticleBySeq(c *gin.Context) {
	seq, _ := strconv.Atoi(c.Query("seq"))
	blogNode, _ := database.QueryBlogBySeq(seq)

	blogPath := fmt.Sprintf("%s/%d.md", blogRoot, seq)
	fileByte, err := ioutil.ReadFile(blogPath)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "msg": err.Error()})
		return
	}

	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4002, "data": "数据库错误"})
		return
	}

	blogNode["text"] = string(fileByte)
	c.JSON(http.StatusOK, gin.H{"code": 200, "data": blogNode})
}
